package org.example.crawler.service;

import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class PythonService {

    @Value("${python.script.path}")
    private String pythonScriptPath;

    @Value("${python.executable:python3}")
    private String pythonExecutable;

    private final ExcelService excelService;

    public PythonService(ExcelService excelService) {
        this.excelService = excelService;
    }

    /**
     * 获取所有可用的关键词组合
     */
    public Map<String, List<String>> getAvailableKeywords() {
        return excelService.readKeywordsFromExcel();
    }

    /**
     * 执行Python脚本
     * @param keyList 关键词组合名称
     * @param sourceType 来源类型编号
     * @return 执行结果
     */
    public String executePythonScript(String keyList, int sourceType) {
        Map<String, List<String>> keywordMap = getAvailableKeywords();

        if (!keywordMap.containsKey(keyList)) {
            return "错误：未找到关键词组合 '" + keyList + "'";
        }

        try {
            // 0. 获取Python脚本所在目录
            File scriptFile = new File(pythonScriptPath);
            String scriptDir = scriptFile.getParent();

            // 1. 构建Python命令（显式指定工作目录）
            ProcessBuilder pb = new ProcessBuilder(
                    pythonExecutable,
                    scriptFile.getName(),  // 使用文件名而非完整路径
                    keyList,
                    String.valueOf(sourceType)
            );

            // 2. 设置工作目录（关键修复！）
            pb.directory(new File(scriptDir));

            // 3. 处理中文路径/输出编码问题
            Map<String, String> env = pb.environment();
            env.put("PYTHONIOENCODING", "UTF-8");
            pb.redirectErrorStream(true);

            // 4. 打印执行的命令（调试用）
            System.out.println("执行命令: " + pb.command() + " | 工作目录: " + pb.directory());

            // 5. 启动进程
            Process process = pb.start();

            // 6. 读取输出（指定编码）
            StringBuilder output = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"))) {  // Windows中文系统用GBK
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }

            // 7. 等待完成（带超时）
            boolean finished = process.waitFor(30, TimeUnit.MINUTES);
            if (!finished) {
                process.destroyForcibly();
                return "执行超时，已终止进程";
            }

            int exitCode = process.exitValue();
            return String.format("执行完成，退出码: %d\n输出:\n%s", exitCode, output.toString());

        } catch (IOException e) {
            return "IO错误: " + e.getMessage() + " (请检查Python路径: " + pythonExecutable + ")";
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return "执行被中断: " + e.getMessage();
        } catch (Exception e) {
            return "未知错误: " + e.getClass().getSimpleName() + " - " + e.getMessage();
        }
    }

    /**
     * 获取关键词组合列表
     */
    public List<String> getKeywordGroups() {
        return new ArrayList<>(getAvailableKeywords().keySet());
    }

    /**
     * 验证关键词组合是否存在
     */
    public boolean validateKeywordGroup(String groupName) {
        return getAvailableKeywords().containsKey(groupName);
    }

    /**
     * 获取平台类型映射
     */
    public Map<Integer, String> getPlatformTypes() {
        return Map.of(
                0, "bilibili",
                1, "微博",
                2, "今日头条",
                3, "Youtube",
                4, "知乎",
                5, "抖音",
                6, "微信公众号",
                7, "快手"
        );
    }
}